//
//  SLNearViewController.m
//  StarLight
//
//  Created by 吴涛 on 16/5/9.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLNearViewController.h"
#import "BKJLocationService.h"
#import "SLLocatinViewController.h"
#import "SLNearlyViewModel.h"
#import "SLMineViewModel.h"
#import "SLNearlyCollectionViewCell.h"
#import <MJRefresh.h>
#import <QMapSearchKit/QMapSearchKit.h>
#import <QMapKit/QMapKit.h>
#import "SLBoatDetailViewController.h"
#import "SLProductDetailViewController.h"
#import "SLMapViewController.h"
#import "SLMessageCenterViewController.h"
#import "SLSearchViewController.h"
#import "SLUserManager.h"






@interface SLNearViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SLNearlyCollectionViewCellDelegate>

@property (nonatomic, strong) BKJLocationService *locationService;

@property (nonatomic, strong) UILabel *currentLocationLabel;

@property (nonatomic, strong) SLNearlyViewModel *nearlyVM;

@property (nonatomic, strong) SLMineViewModel *mineVM;

@property (nonatomic, strong) UICollectionView *nearlyCollectionView;

@property (nonatomic, strong) CLLocation *currentLocation;

@property (nonatomic, strong) UIButton *searchBtn;

@property (nonatomic, strong) UIButton *msgBtn;

@property (nonatomic ,strong) UIButton *backBtn;

@end

@implementation SLNearViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mineVM = [SLMineViewModel shareInstance];
    [self setUpUI];
    [self checkLocation];
    [self addObservers];
    [self addLoadMoreAndRefresh];
  
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  self.view.backgroundColor = [UIColor defeutBackgroudColor];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


- (void)updateVersion{
  
  UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"为了您更好的体验我们的产品，请升级到最新版本" preferredStyle:UIAlertControllerStyleAlert];
  UIAlertAction *confimAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/xin-ma-tou/id1127764076?mt=8"]];
  }];
  [alertVC addAction:confimAction];
  
  [self.tabBarController presentViewController:alertVC animated:YES completion:nil];
  
}

- (void)addObservers{
  @weakify(self)
  
  // 更新版本
  [SLUserManager checkVersionSuccess:^(NSString  *version) {
    @strongify(self)
    if (![version isEqualToString:kAPPVersion]) {
      [self updateVersion];
    }
  }];
  
  self.nearlyCollectionView.emptyDataSetSource = self;
  self.nearlyCollectionView.emptyDataSetDelegate = self;
  if (self.mineVM.indexModel.type == 0 ) {
    // 如果是船主 则要显示 货物信息
    self.nearlyVM = [[SLNearlyViewModel alloc] initWithPage:@1  andType:NearlyViewModelTypeProduct];
  }else if (self.mineVM.indexModel.type == 1){
    // 如果是货主 则要显示 船信息
    self.nearlyVM = [[SLNearlyViewModel alloc] initWithPage:@1  andType:NearlyViewModelTypeShip];
  }

  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"changeLocation" object:nil] subscribeNext:^(NSNotification *notify) {
    @strongify(self)
    QMSPoiData *poiData = notify.userInfo[@"location"];
    self.currentLocationLabel.text = poiData.address;
    [self.nearlyVM changeLocationWithLon:poiData.location.longitude lat:poiData.location.latitude];
  }];
  
  [RACObserve( self.locationService, adress) subscribeNext:^(NSString *newAddress) {
    @strongify(self)
    self.currentLocationLabel.text = newAddress;
  }];
  
  
  [[RACObserve( self.locationService, currentLocation)filter:^BOOL(id value) {
    return value != nil;
  }] subscribeNext:^(CLLocation *location) {
    @strongify(self)
    self.currentLocation = location;
  }];
  
  [[RACObserve(self.locationService, currentLocation) filter:^BOOL(id value) {
    return value != nil;
  }] subscribeNext:^(CLLocation *location) {
    @strongify(self)
    [self.nearlyVM changeLocationWithLon:location.coordinate.longitude lat:location.coordinate.latitude];
  }];
  
  
  [[RACObserve(self.nearlyVM, dataSource) filter:^BOOL(NSMutableArray *value) {
    return value != nil;
  }] subscribeNext:^(NSMutableArray *dataArr) {
    @strongify(self)
    [self setUpStauts];
  }];

}

- (void)addLoadMoreAndRefresh{
  @weakify(self)
  self.nearlyCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    @strongify(self)
    [self.nearlyVM first];
    [self.nearlyCollectionView.footer resetNoMoreData];
  }];
  
  self.nearlyCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
    @strongify(self)
    [self.nearlyVM next];
  }];

}

- (void)setUpStauts{
  
  [self.nearlyCollectionView reloadData];
  if (self.nearlyVM.dataSource.count % 10 > 0) {
    [self.nearlyCollectionView.footer endRefreshingWithNoMoreData];
  }else{
    [self.nearlyCollectionView.footer endRefreshing];
  }
  
  [self.nearlyCollectionView.header endRefreshing];
  
  [SVProgressHUD dismiss];
}

#pragma mark - SLNearlyCollectionViewCellDelegate

- (void)currentBtnWasTapedWithShipModel:(SLNearLyShip *)shipModel{
  SLMapViewController *mapVC = [SLMapViewController new];
  if (shipModel.state == 3) {
    [mapVC locationWithLon:shipModel.goallon lat:shipModel.goallat];
  }else{
    [mapVC locationWithLon:shipModel.shiplon lat:shipModel.shiplat];
  }
  
  [self.navigationController pushViewController:mapVC animated:YES];
}


#pragma mark - setUpUI
- (void)setUpUI{
  
  UIView *locationView = [UIView new];
  locationView.backgroundColor = [UIColor whiteColor];
  locationView.layer.cornerRadius = 28/2.f;
  [self.view addSubview:locationView];
  [locationView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.naviHeader.mas_bottom).offset(5);
    make.centerX.equalTo(self.view);
    make.width.equalTo(self.view).offset(-22);
    make.height.equalTo(@28);
  }];
  
  UIImageView *leftImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"currentLocation"]];
  UIImageView *rightImgeView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"next"]];
  UILabel *tipLabel = [UILabel labelWithFontSize:12 textColor:[UIColor grayColor] text:@"当前位置："];
  
  [locationView addSubview:leftImageView];
  [locationView addSubview:tipLabel];
  [locationView addSubview:self.currentLocationLabel];
  [locationView addSubview:rightImgeView];
  
  
  [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.size.mas_equalTo(CGSizeMake(16, 18));
    make.centerY.equalTo(locationView);
    make.left.equalTo(locationView).offset(14);
  }];
  
  [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(leftImageView.mas_right).offset(5);
    make.centerY.equalTo(locationView);
  }];
  
  [rightImgeView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.size.mas_equalTo(CGSizeMake(16, 16));
    make.centerY.equalTo(locationView);
    make.right.equalTo(locationView).offset(-14);
  }];
  
  [self.currentLocationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.equalTo(tipLabel.mas_right).offset(1);
    make.right.equalTo(rightImgeView.mas_left).offset(1);
    make.centerY.equalTo(locationView);
  }];
  
  UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toSkipMapViewController)];
  
  [locationView addGestureRecognizer:tapGes];
  
  [self.view addSubview:self.nearlyCollectionView];
  [self.nearlyCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.width.centerX.equalTo(self.view);
    make.top.equalTo(locationView.mas_bottom).offset(5);
    make.bottom.equalTo(self.mas_bottomLayoutGuideTop).offset(-2);
  }];
  
  [self.naviHeader addSubview:self.msgBtn];
  [self.naviHeader addSubview:self.searchBtn];
    [self.naviHeader addSubview:self.backBtn];
  
  [self.searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.naviHeader.leftLabel);
    make.right.equalTo(self.naviHeader).offset(-15);
    make.size.mas_equalTo(CGSizeMake(25, 25));
  }];
  [self.msgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.naviHeader.leftLabel);
    make.right.equalTo(self.searchBtn.mas_left).offset(-15);
    make.size.equalTo(self.searchBtn);
  }];
  [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.naviHeader.leftLabel);
    make.left.equalTo(self.naviHeader.mas_left).offset(15);
    make.size.equalTo(self.searchBtn);
  }];
      
  
}

- (void)showSearchVC{
  SLSearchViewController *searchVC = [SLSearchViewController new];
  [self.tabBarController.navigationController pushViewController:searchVC animated:YES];
}

- (void)showMessageCenter{
  SLMessageCenterViewController *msgCenterVC = [SLMessageCenterViewController new];
  [self.tabBarController.navigationController pushViewController:msgCenterVC animated:YES];
}
- (void)exitPopView{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 检查位置

- (void)checkLocation{
  
  
  if (![CLLocationManager locationServicesEnabled]) {
    self.currentLocationLabel.text = @"定位服务尚未启用";
    [SVProgressHUD showImage:nil status:@"定位服务尚未启用"];
    return;
  }
  self.locationService = [BKJLocationService shareService];
  
  
}

#pragma mark - Private Method

- (void)toSkipMapViewController{
  SLLocatinViewController *locationVC = [SLLocatinViewController new];
  [self.tabBarController.navigationController pushViewController:locationVC animated:YES];
}


- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
  
  if (![CLLocationManager locationServicesEnabled]) {
    return [[NSAttributedString alloc] initWithString:@"请选择您所查询的位置" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];  }
  
  if (!self.reach.isReachable) {
    return [[NSAttributedString alloc] initWithString:@"无网络连接, 请连接网络后刷新" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
  }
  
  if (self.mineVM.indexModel.type == 0 ) {
    // 如果是船主 则要显示 货物信息
    return [[NSAttributedString alloc] initWithString:@"暂无附近货源信息" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
  }else if (self.mineVM.indexModel.type == 1){
    // 如果是货主 则要显示 船信息
    return [[NSAttributedString alloc] initWithString:@"暂无附近船舶信息" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
  }

  return nil;
}

//- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state{
//  return [[NSAttributedString alloc] initWithString:@"点击刷新"];
//}



- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView{
  DLog(@"点击了。。。。。。。。。");
  [self.nearlyCollectionView.header beginRefreshing];
  [self.nearlyVM first];
}



#pragma mark UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  return  self.nearlyVM.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
  SLNearlyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  
  if (self.mineVM.indexModel.type == 0) {
    [cell configWithType:NearlyCellTypeShip];
  }else{
    [cell configWithType:NearlyCellTypeProduct];
  }
  cell.delegate = self;
  return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
  SLNearlyCollectionViewCell *thisCell = (SLNearlyCollectionViewCell *)cell;
  if (self.mineVM.indexModel.type == 0) {
    [thisCell configNearlyCellWithProductModel:self.nearlyVM.dataSource[indexPath.row]];
  }else{
    [thisCell configNearlyCellWithShipModel:self.nearlyVM.dataSource[indexPath.row]];
  }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  
  SLNearlyCollectionViewCell *cell = (SLNearlyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
  cell.backgroundColor = [UIColor lightGrayColor];
  
  if (self.mineVM.indexModel.type == 0 ) {
    // 如果是船主 则要显示 货物信息
    SLNearLyProduct *model = self.nearlyVM.dataSource[indexPath.row];
    SLProductDetailViewController *productDVC = [SLProductDetailViewController new];
    [productDVC changeGid:model.gid];
    [self.tabBarController.navigationController pushViewController:productDVC animated:YES];
  }else if (self.mineVM.indexModel.type == 1){
    // 如果是货主 则要显示 船详细信息
    SLNearLyShip *model = self.nearlyVM.dataSource[indexPath.row];;
    SLBoatDetailViewController *boatDVC = [SLBoatDetailViewController new];
    [boatDVC changeBid:model.bid];
    [self.tabBarController.navigationController pushViewController:boatDVC animated:YES];
  }
  
  cell.backgroundColor = [UIColor whiteColor];

}





#pragma mark getter


- (UILabel *)currentLocationLabel{
  if (!_currentLocationLabel) {
    _currentLocationLabel = [UILabel labelwithBoldFontSize:12 textColor:[UIColor blackColor] text:@""];
  }
  return _currentLocationLabel;
}

- (SLMineViewModel *)mineVM{
  
//  if (!_mineVM) {
    _mineVM = [SLMineViewModel shareInstance];
  
//  }
  return _mineVM;
}


- (UICollectionView *)nearlyCollectionView{
  if (!_nearlyCollectionView) {
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH-20, 140);
    _nearlyCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _nearlyCollectionView.backgroundColor = [UIColor defeutBackgroudColor];
    [_nearlyCollectionView registerClass:[SLNearlyCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    _nearlyCollectionView.delegate = self;
    _nearlyCollectionView.dataSource = self;
  }
  return _nearlyCollectionView;
}


- (UIButton *)searchBtn{
  if (!_searchBtn) {
    _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_searchBtn setImage:[UIImage imageNamed:@"search icon"] forState:UIControlStateNormal];
    [_searchBtn addTarget:self action:@selector(showSearchVC) forControlEvents:UIControlEventTouchUpInside];
  }
  return _searchBtn;
}

- (UIButton *)msgBtn{
  if (!_msgBtn) {
    _msgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_msgBtn setImage:[UIImage imageNamed:@"information icon"] forState:UIControlStateNormal];
    [_msgBtn addTarget:self action:@selector(showMessageCenter) forControlEvents:UIControlEventTouchUpInside];
  }
  return _msgBtn;
}


- (UIButton *)backBtn
{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(exitPopView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

@end
